﻿using System.Linq;
using System.Web.Mvc;
using System.Web;
using System.Net;
using System.IO;
using System;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Data.Linq;
using GuildStock.Controllers;
using GuildStock.Models;
using GuildStock.Services.JsonToDynamic;
using GuildStock.Services.Blizzard;

namespace GuildStock.Services
{
    /// <summary>
    /// Guild processing logic.
    /// </summary>
    public class GuildProcessor
    {
        public void LoadGuildAsync(string guildName, string realm)
        {
          var zone = realm.ExtractZone();
          var guildJSON = new BlizzardService().GetGuildMembers(guildName, realm.ExtractRealmName(), zone);
          var guild = JsonHelper.ConvertJsonToDynamic(guildJSON);

          if (guild != null)
          {
            var context = new GuildStockDataDataContext();

            var previousRecord = context.Guilds
              .Where(g => g.GuildName == guildName && g.RealmName == realm)
              .OrderByDescending(g => g.Updated)
              .FirstOrDefault();

            var newGuild = new Guild();
            newGuild.id = Guid.NewGuid();
            newGuild.GuildName = guild.name;
            newGuild.RealmName = ZonesExtensions.FullName(guild.realm, zone);
            newGuild.Fraction = guild.side == 0 ? "A" : "H";
            newGuild.Sign = this.GetSignForTheGuild();
            newGuild.Score = guild.members.Count;
            newGuild.Rank = -1;
            newGuild.g_In = -1;
            newGuild.g_Out = -1;
            newGuild.g_Progress = previousRecord != null ? (int)(newGuild.Score - previousRecord.Score) : 0;
            newGuild.Updated = DateTime.Now;

            context.Guilds.InsertOnSubmit(newGuild);

            context.SubmitChanges();

            this.RecalculateRealmRank(realm);
          }
        }

        public Binary GetSignForTheGuild()
        {
          return null;
        }

        public void RecalculateRealmRank(string realm)
        {
          var context = new GuildStockDataDataContext();

          var guilds = context.Guilds
            .Where(i => i.RealmName == realm)
            .OrderByDescending(i => i.Updated)
            .ToList()
            .Distinct(new GuildComparer())
            .OrderByDescending(i => i.Score)
            .ToList();

          for (int i = 0; i < guilds.Count; i++)
          {
            guilds[i].Rank = i + 1;
          }

          context.SubmitChanges();
        }
    }
}
